package com.kai.steering.data.service.ctl;

import cn.hutool.core.bean.BeanUtil;
import com.kai.steering.data.service.entity.domainObject.QuestionDO;
import com.kai.steering.data.service.entity.domainObject.TestDO;
import com.kai.steering.data.service.entity.dto.TestDTO;
import com.kai.steering.data.service.entity.dto.TestQueryDTO;
import com.kai.steering.data.service.entity.po.Test;
import com.kai.steering.data.service.entity.vo.TestVO;
import com.kai.steering.data.service.service.TestService;
import com.kai.steering.common.vo.Result;
import com.kai.steering.common.web.ctl.BaseController;
import com.kai.steering.data.service.util.EqualsUtil;
import com.kai.steering.exception.CanUsedException;
import com.kai.steering.exception.ExcelException;
import com.kai.steering.exception.UimpException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


import java.io.IOException;
import java.io.Serializable;
import javax.annotation.Resource;
import javax.validation.Valid;

import com.kai.steering.common.vo.Page;
import com.kai.steering.common.web.vo.ReturnCodeExt;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <pre>
 * 试卷 前端控制器
 * </pre>
 *
 * @author kai
 * @since 2022-02-23
 */
@Slf4j
@RestController
@RequestMapping("/test")
@Api(tags = "试卷 API")
public class TestController extends BaseController {
    @Autowired
    private TestService testService;


    @PostMapping
    @ApiOperation(value = "试卷-添加")
    public Result<TestDO> addTest(@Valid @RequestBody TestDTO testDTO) {
        //参数检查
        if (StringUtils.isEmpty(testDTO.getTestName())) {
            throw ReturnCodeExt.PARAMETER_CHECK.getException("属性不全");
        }
        //构建新对象
        TestDO testDO = new TestDO(testDTO);
        testDO.setTestId(null);
        testDO.setQuestions(null);
        TestDO test = testService.saveTest(testDO);
        if (test != null) {
            return Result.ok(test);
        }
        return Result.failed();
    }


    @PutMapping("/{id}")
    @ApiOperation(value = "试卷-编辑")
    public Result<Boolean> updateTest(@PathVariable("id") Serializable id, @Valid @RequestBody TestDTO testDTO) {
        //参数检查
        if (StringUtils.isEmpty(testDTO.getTestName()) || StringUtils.isEmpty(id.toString())) {
            return Result.failed("属性不全");
        }
        //构建新对象
        TestDO testDO = new TestDO(testDTO);
        testDO.setTestId(id.toString());
        //修改属性
        boolean flag = testService.updateTest(id, testDO);
        return Result.ok(flag);
    }


    @DeleteMapping("/{id}")
    @ApiOperation(value = "试卷-删除")
    public Result<Boolean> deleteTest(@PathVariable("id") Serializable id) {

        boolean flag = testService.deleteTest(id);
        return Result.ok(flag);
    }


    @PostMapping("/{id}")
    @ApiOperation(value = "试卷-详情:knowledgeExist,subjectExist")
    public Result<TestVO> getTest(@PathVariable("id") Serializable id, @RequestBody Map parameterList) {
        if (StringUtils.isEmpty(id.toString())) {
            return Result.failed("id为空");
        }
        HashMap<String, Boolean> parameterMap = new HashMap<>();
        boolean knowledgeExist = false;
        if (EqualsUtil.objectEquals(parameterList.get("knowledgeExist"), "1", 1)) {

            knowledgeExist = true;
        }
        parameterMap.put("knowledgeExist", knowledgeExist);
        boolean questionExist = false;
        boolean questionKnowledgeExist = false;
        boolean questionsAnswerExist = false;

        boolean questionDetailsExist = false;

        boolean questionUserExist = false;

        if (EqualsUtil.objectEquals(parameterList.get("questionExist"), "1", 1)) {
            questionExist = true;
            parameterMap.put("questionExist", questionExist);
            if (EqualsUtil.objectEquals(parameterList.get("questionUserExist"), "1", 1)) {
                questionUserExist = true;

            }
            parameterMap.put("questionUserExist", questionUserExist);
            if (EqualsUtil.objectEquals(parameterList.get("questionDetailsExist"), "1", 1)) {
                questionDetailsExist = true;
            }
            parameterMap.put("questionDetailsExist", questionDetailsExist);
            if (EqualsUtil.objectEquals(parameterList.get("questionKnowledgeExist"), "1", 1)) {
                questionKnowledgeExist = true;
            }
            parameterMap.put("questionKnowledgeExist", questionKnowledgeExist);
            if (EqualsUtil.objectEquals(parameterList.get("questionsAnswerExist"), "1", 1)) {
                questionsAnswerExist = true;
            }
            parameterMap.put("questionsAnswerExist", questionsAnswerExist);
        }


        TestVO testQueryVo = new TestVO(testService.getTestById(id, parameterMap));
        return Result.ok(testQueryVo);
    }


    @PostMapping("/list")
    @ApiOperation(value = "试卷-综合查询")
    public Result<Page<TestVO>> getTestPageList(@Valid @RequestBody TestQueryDTO testQueryParam) {
        Page<TestDO> paging = testService.getTestPageList(testQueryParam);


        List<TestVO> result = paging.getList().stream()
                .map(test -> {
                    TestVO testVO = new TestVO();
                    BeanUtil.copyProperties(test, testVO);
                    return testVO;
                })
                .collect(Collectors.toList());
        Page<TestVO> build = Page.<TestVO>builder()
                .currPage(paging.getCurrPage())
                .pageSize(paging.getPageSize())
                .totalCount(paging.getTotalCount())
                .list(result)
                .build();
        return Result.ok(build);
    }


    @GetMapping("/list")
    @ApiOperation(value = "试卷-全部列表")
    public Result<List<TestVO>> getTestAllList() {

        List<TestDO> allTest = testService.getAllTest();
        List<TestVO> testVOS = TestVO.convertTestVO(allTest);

        return Result.ok(testVOS);
    }


    @PostMapping("/exportTest")
    @ApiOperation(value = "试卷-导出题目")
    public Result<Boolean> exportTest(List<String> testIds) {
        return Result.ok(testService.exportTest(testIds));
    }

    @PostMapping("/importQuestion/{testID}")
    @ApiOperation(value = "试卷-导入题目文件")
    public ResponseEntity<Resource> importQuestion(@RequestParam("file") MultipartFile file, @PathVariable("testID") Serializable testID) {
        // 检查上传文件是否为空
        if (file.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        }

        // 检查文件类型，根据你的需求，你可以检查扩展名或者 MIME 类型
        String contentType = file.getContentType();
        String filename = file.getOriginalFilename();

        // 这里只是一个简单的示例，判断文件名后缀是否为Excel格式，一般为 .xls 或 .xlsx
        if (filename == null || !(filename.endsWith(".xls") || filename.endsWith(".xlsx"))) {
            return ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
                    .body(null); // 415 状态码表示不支持的媒体类型
        }
        try {

            testService.importQuestion(testID.toString(),file );
        } catch (CanUsedException canUsedException) {
            List<ExcelException> excelExceptions = (List<ExcelException>) canUsedException.getData();
            if (excelExceptions.size() > 0) {
                try {
                    ResponseEntity responseEntity = UimpException.generateResponse(file, excelExceptions);
                    return responseEntity;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        ResponseEntity successResource = ResponseEntity.ok("导入成功");
        return successResource;
    }

    @PostMapping("/exportQuestion/{testID}")
    @ApiOperation(value = "试卷-导入题目")
    public Result<Boolean> exportQuestion(@Valid @RequestBody List<String> questionsIDs, @PathVariable("testID") Serializable testID) {
        if (StringUtils.isEmpty(testID.toString())) {
            return Result.failed("testID为空");
        }
        if (StringUtils.isEmpty(questionsIDs.toString()) || questionsIDs.size() == 0) {
            return Result.failed("id为空");
        }
        testService.exportQuestion(testID.toString(), questionsIDs);
        return Result.ok();
    }
}